<template>
  <div>
    <el-form @submit.native.prevent :inline="true">
      <el-form-item>
        <select-address
          v-model="queryParams.addressCode"
          placeholder="地址查询"
          auto-top
          clearable
          :bottom-level="2"
          @change="handleQuery"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="formData.dateRange"
          type="monthrange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          @change="handleQuery"
        ></el-date-picker>
      </el-form-item>
      <!-- <el-form-item>
        <select-org-bank v-model="formData.bankId"
                         placeholder="选择银行"
                         filterable
                         clearable
                         @select="selectBank"></select-org-bank>
      </el-form-item> -->
      <el-form-item>
        <el-button :loading="loading" icon="el-icon-search" @click="listGetData()">查询</el-button>
        <!-- <el-button :loading="downloadLoading"
                   icon="el-icon-download"
                   @click="exportExcel()">下载</el-button> -->
      </el-form-item>
    </el-form>

    <div class="w-100">
      <el-echarts
        theme="macarons"
        :loading="loading"
        :height="450"
        :option="chartOption"
      ></el-echarts>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getMonthLastDayDate } from '@/common/plugins/tools/date'

import { echartsXFormatter } from '@vimi/utils-tool'

import SelectAddress from '@/components/select/SelectAddress'
// import SelectOrgBank from '@/bigcredit/views/program/components/SelectOrgBank'

export default {
  components: {
    SelectAddress,
    // SelectOrgBank,
  },
  props: {},
  data() {
    return {
      loading: false,
      downloadLoading: false,
      formData: {
        dateRange: [],
        bankId: '',
        busType: '',
      },
      queryParams: {
        clientId: '',
        addressCode: '',
        startDate: '',
        endDate: '',
        bankCode: '',
        busStatus: '',
        guaType: '1,2,3,4',
      },

      chartOption: {},
    }
  },
  computed: {
    ...mapGetters(['clientId']),
  },
  watch: {},
  created() {
    this.setDateParams()
    this.getData()
  },
  mounted() {},
  methods: {
    setDateParams() {
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth()

      let startYear = year - 1
      let startMonth = month + 1
      if (startMonth === 12) {
        startYear++
        startMonth = 0
      }
      const start = new Date(startYear, startMonth, 1)
      const end = getMonthLastDayDate(year, month)

      this.formData.dateRange = [start, end]
      this.queryParams.startDate = start
      this.queryParams.endDate = end
      this.queryParams.clientId = this.clientId
    },
    async getData() {
      const params = {
        load_name: '',
        'service_id.eq': 'COMMON_PRODUCT',
        'orWhere.db_service_id.eq': this.clientId,
        'orWhere.db_service_id.is': 'null',
      }

      // const { addressCode = '', startDate, endDate } = this.queryParams
      // const addressLevel = getAddressLevel(addressCode)
      // if (addressLevel === 2) {
      //   params['county_code.eq'] = addressCode.substring(0, 6)
      // } else if (addressLevel === 1) {
      //   params['city_code.eq'] = addressCode.substring(0, 4)
      // }

      // if (startDate && endDate) {
      //   const startYear = startDate.getFullYear()
      //   const startMonth = startDate.getMonth() + 1
      //   const endYear = endDate.getFullYear()
      //   const endMonth = endDate.getMonth() + 1
      //   params['load_date_ny.gte'] = startYear + `${startMonth}`.padStart(2, '0')
      //   params['load_date_ny.lte'] = endYear + `${endMonth}`.padStart(2, '0')
      // }

      const sumKeys = ['project_num', 'reply_funds_total', 'left_funds_total']
      const groupFunc = sumKeys
        .reduce((a, b) => {
          a.push(`round(sum(${b}))`)
          return a
        }, [])
        .join(',')
      const fields = ['industrial_package_id', 'project_num', 'left_funds_total', 'load_name']

      params.fields = fields
      params.groupFunc = groupFunc
      params.groupFields = ['industrial_package_id']

      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, 'industrial_package_total_view', params)
      )
      this.loading = false

      const data = (res && res.data) || []

      const xData = []
      // 在何
      const aData = []
      const bData = []
      // 解保
      const cData = []
      const dData = []
      // 新增
      const eData = []
      const fData = []
      // 代偿
      const gData = []
      const hData = []

      for (const item of data) {
        xData.push(item.load_name)
      }

      this.setOption({
        xData,
        aData,
        bData,
        cData,
        dData,
        eData,
        fData,
        gData,
        hData,
      })
    },
    listGetData() {
      const { listRef } = this.$refs
      if (listRef) {
        listRef.getData()
      }
      this.getData()
    },

    exportExcel() {
      const { listRef } = this.$refs
      if (listRef) {
        this.downloadLoading = true
        listRef.exportExcel().finally(() => {
          this.downloadLoading = false
        })
      }
    },

    handleQuery() {
      const { dateRange, busType } = this.formData

      // 时间处理
      if (!dateRange) {
        this.setDateParams()
      } else {
        this.queryParams.startDate = dateRange[0]
        this.queryParams.endDate = getMonthLastDayDate(
          dateRange[1].getFullYear(),
          dateRange[1].getMonth()
        )
      }

      // 业务类型
      this.queryParams.guaType = busType === 1 ? '3' : busType === 0 ? '1,2,4' : '1,2,3,4'

      this.getData()
    },
    selectBank(bank) {
      this.queryParams.bankCode = bank.agency_code || ''
      this.getData()
    },
    setOption(data) {
      this.chartOption = {
        title: {
          text: '产品统计',
          subtext: '',
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: [
            '在保项目',
            '解保项目',
            '新增项目',
            '代偿项目',
            '在保金额',
            '解保金额',
            '新增金额',
            '代偿金额',
          ],
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        grid: {
          top: 80,
          left: 50,
          right: 80,
          bottom: 80,
        },
        xAxis: [
          {
            type: 'category',
            data: data.xData,
            axisLabel: {
              formatter: v => echartsXFormatter(v, 4),
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '项目数（个）',
          },
          {
            type: 'value',
            name: '金额（万元）',
          },
        ],
        series: [
          {
            name: '在保项目',
            type: 'bar',
            yAxisIndex: 0,
            data: data.aData,
            label: { show: true, position: 'top' },
          },
          {
            name: '解保项目',
            type: 'bar',
            yAxisIndex: 0,
            data: data.cData,
            label: { show: true, position: 'top' },
          },
          {
            name: '新增项目',
            type: 'bar',
            yAxisIndex: 0,
            data: data.eData,
            label: { show: true, position: 'top' },
          },
          {
            name: '代偿项目',
            type: 'bar',
            yAxisIndex: 0,
            data: data.gData,
            label: { show: true, position: 'top' },
          },
          {
            name: '在保金额',
            type: 'line',
            yAxisIndex: 1,
            data: data.bData,
            label: { show: false, position: 'inside' },
          },
          {
            name: '解保金额',
            type: 'line',
            yAxisIndex: 1,
            data: data.dData,
            label: { show: false, position: 'inside' },
          },
          {
            name: '新增金额',
            type: 'line',
            yAxisIndex: 1,
            data: data.fData,
            label: { show: false, position: 'inside' },
          },
          {
            name: '代偿金额',
            type: 'line',
            yAxisIndex: 1,
            data: data.hData,
            label: { show: false, position: 'inside' },
          },
        ],
      }
    },
  },
}
</script>

<style lang="scss" scoped></style>
